<?php

namespace Modules\Core\Models;

use App\Models\BaseModel;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Modules\Core\Http\Filters\DepartmentFilter;
use Modules\Core\Http\Filters\RoleFilter;
use Spatie\Permission\Traits\HasRoles;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends BaseModel implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use HasFactory;
    use Notifiable;
    use BelongsToTenant;
    use HasRoles;
    // use HasSocial; // 社交模块
    // use MustVerifyEmail; 邮箱验证
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'core_users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'mobile','mobile_verified_at','create_ip_at', 'tenant_id',
        'last_login_at','last_login_ip_at','login_times','status','nickname','avatar', 'username', 'is_admin', 'level'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'mobile_verified_at' => 'datetime',
        'is_admin' => 'boolean'
    ];

    /**
     * @return string[]
     */
    protected function filters()
    {
        return [
            'depart_id' => DepartmentFilter::class,
            'role_id' => RoleFilter::class,
        ];
    }

    /**
     * 获取用户姓名
     * 优先级 username => nickname => name
     * @return mixed
     */
    public function getName($mobileFirst = false)
    {
        return $this->mobile&&$mobileFirst
            ? $this->mobile
            : ($this->username ?: ($this->nickname ?: ( $this->name ?: '' )));
    }

    /**
     * @return bool
     */
    public function isSuper()
    {
        return true;
    }

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->create_ip_at = $model->create_ip_at ?? request()->ip();
        });
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function departments()
    {
        return $this->belongsToMany(Department::class, 'core_department_user');
    }
}
